<template>
  <div class="medical-record-parser">
    <div class="parser-header">
      <div class="title-section">
        <h1 class="page-title">TXT解析工具</h1>
        <p class="page-desc">将病历TXT文本或文件上传进行结构化处理，支持一站式处理和分步处理两种模式</p>
      </div>

    <!-- 处理模式选择 -->
    <div class="process-mode">
      <el-radio-group v-model="processMode" @change="resetResults">
        <el-radio label="oneStop">一站式处理</el-radio>
        <el-radio label="stepByStep">分步处理</el-radio>
      </el-radio-group>
      </div>
    </div>

    <!-- 主内容区域 - 左右布局 -->
    <div class="main-content-layout">
      <!-- 左侧 - 输入区域 -->
      <div class="input-section">
        <h3 class="section-title">输入区域</h3>
    <!-- 输入方式选择 -->
    <div class="input-mode-tabs">
      <el-tabs v-model="inputMode" @tab-click="resetResults">
        <el-tab-pane label="文本输入方式" name="text">
              <div class="text-input-container">
          <el-input
            type="textarea"
            :rows="10"
                  placeholder="请输入病历TXT文本内容..."
            v-model="textContent"
            :disabled="loading"
                  class="text-input"
          />
                <div class="text-actions" v-if="textContent">
                  <el-button size="small" type="primary" plain @click="detectTextEncoding" :disabled="loading">
                    检测编码问题
                  </el-button>
                  <el-button size="small" @click="textContent = ''" :disabled="loading">清空文本</el-button>
                </div>
              </div>
        </el-tab-pane>
        <el-tab-pane label="文件上传方式" name="file">
          <el-upload
            class="upload-area"
            drag
            action="#"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            :on-change="handleFileChange"
                :on-remove="handleFileRemove"
            :disabled="loading"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
                  将TXT文件拖到此处，或<em>点击上传</em>
            </div>
                <div class="el-upload__tip">
              支持TXT文本文件，最大50MB
            </div>
          </el-upload>
              <div class="file-info" v-if="fileList.length > 0">
                <span>已选择文件: {{ fileList[0].name }}</span>
                <el-button size="small" type="primary" plain @click="previewFileContent" :disabled="loading">
                  预览文件内容
                </el-button>
              </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 处理按钮 -->
    <div class="action-buttons">
      <el-button 
        type="primary" 
        @click="processRecord" 
        :disabled="!canProcess || loading" 
        :loading="loading">
        {{ processMode === 'oneStop' ? '一站式处理' : '开始分步处理' }}
      </el-button>
      <el-button @click="resetAll" :disabled="loading">重置</el-button>
          <el-tooltip content="检查服务连接状态" placement="top" v-if="!loading">
            <el-button icon="el-icon-refresh" circle size="small" @click="checkServiceStatus"></el-button>
          </el-tooltip>
        </div>
      </div>

      <!-- 右侧 - 结果区域 -->
      <div class="result-section">
        <h3 class="section-title">处理结果</h3>

        <!-- 服务状态显示 -->
        <div class="service-status" v-if="serviceStatus !== 'checking'">
          <el-tag :type="serviceStatus === 'ok' ? 'success' : 'danger'" size="small">
            {{ serviceStatus === 'ok' ? '服务已连接' : '服务未连接' }}
          </el-tag>
        </div>

        <!-- 加载状态显示 -->
        <div v-if="loading" class="loading-container">
          <el-progress 
            :percentage="progressPercentage" 
            :status="progressPercentage >= 100 ? 'success' : ''" 
            :stroke-width="15"
          />
          <div class="loading-text">
            <span>{{ loadingText }}</span>
            <p v-if="loadingTime > 10" class="loading-tip">
              处理中，请耐心等待... ({{ Math.floor(loadingTime) }}秒)
            </p>
            <p v-if="loadingTime > 30" class="loading-tip warning">
              大型文本处理可能需要较长时间，请不要关闭页面
            </p>
          </div>
    </div>

    <!-- 一站式处理结果 -->
        <div v-if="processMode === 'oneStop' && fullResult" class="result-content">
      <div class="json-result">
        <div class="json-header">
          <span>结构化JSON</span>
              <div class="json-actions">
                <el-button size="mini" type="primary" plain @click="copyToClipboard(fullResult)">复制结果</el-button>
                <el-button size="mini" type="success" plain @click="downloadJSON(fullResult, '病历结构化结果.json')">下载JSON</el-button>
              </div>
        </div>
            <pre class="json-output">{{ formatJSON(fullResult) }}</pre>
      </div>
    </div>

    <!-- 分步处理结果 -->
    <div v-if="processMode === 'stepByStep'" class="step-results">
      <!-- 步骤1: 提取键结构 -->
      <el-collapse v-model="activeCollapse" accordion>
        <el-collapse-item name="step1">
          <template #title>
            <div class="step-header">
              <span class="step-number">步骤1</span>
              <span class="step-title">提取病历键结构</span>
              <el-tag v-if="step1Result" size="small" type="success">已完成</el-tag>
            </div>
          </template>
          <div v-if="!step1Result && !loading" class="step-action">
            <el-button type="primary" size="small" @click="extractKeys" :disabled="!canProcess || loading">
              提取键结构
            </el-button>
          </div>
          <div v-if="step1Result" class="json-result step-result">
            <div class="json-header">
              <span>键结构JSON</span>
                  <div class="json-actions">
                    <el-button size="mini" type="primary" plain @click="copyToClipboard(step1Result)">复制结果</el-button>
                    <el-button size="mini" type="success" plain @click="downloadJSON(step1Result, '键结构.json')">下载</el-button>
                  </div>
            </div>
                <pre class="json-output">{{ formatJSON(step1Result) }}</pre>
          </div>
        </el-collapse-item>

        <!-- 步骤2: 匹配模板 -->
        <el-collapse-item name="step2" :disabled="!step1Result">
          <template #title>
            <div class="step-header">
              <span class="step-number">步骤2</span>
              <span class="step-title">匹配病历模板</span>
              <el-tag v-if="step2Result" size="small" type="success">已完成</el-tag>
            </div>
          </template>
          <div v-if="!step2Result && !loading" class="step-action">
            <el-button type="primary" size="small" @click="matchTemplate" :disabled="!step1Result || loading">
              匹配模板
            </el-button>
          </div>
          <div v-if="step2Result" class="json-result step-result">
            <div class="json-header">
              <span>模板匹配结果</span>
                  <div class="json-actions">
                    <el-button size="mini" type="primary" plain @click="copyToClipboard(step2Result)">复制结果</el-button>
                    <el-button size="mini" type="success" plain @click="downloadJSON(step2Result, '模板.json')">下载</el-button>
                  </div>
            </div>
                <pre class="json-output">{{ formatJSON(step2Result) }}</pre>
          </div>
        </el-collapse-item>

        <!-- 步骤3: 生成完整JSON -->
        <el-collapse-item name="step3" :disabled="!step2Result">
          <template #title>
            <div class="step-header">
              <span class="step-number">步骤3</span>
              <span class="step-title">生成完整病历JSON</span>
              <el-tag v-if="step3Result" size="small" type="success">已完成</el-tag>
            </div>
          </template>
          <div v-if="!step3Result && !loading" class="step-action">
            <el-button type="primary" size="small" @click="generateFullRecord" :disabled="!step2Result || loading">
              生成完整JSON
            </el-button>
          </div>
          <div v-if="step3Result" class="json-result step-result">
            <div class="json-header">
              <span>完整病历JSON</span>
                  <div class="json-actions">
                    <el-button size="mini" type="primary" plain @click="copyToClipboard(step3Result)">复制结果</el-button>
                    <el-button size="mini" type="success" plain @click="downloadJSON(step3Result, '完整病历.json')">下载</el-button>
                  </div>
            </div>
                <pre class="json-output">{{ formatJSON(step3Result) }}</pre>
          </div>
        </el-collapse-item>
      </el-collapse>
        </div>
      </div>
    </div>

    <!-- 文件预览对话框 -->
    <el-dialog
      title="文件内容预览"
      v-model="filePreviewVisible"
      width="80%">
      <div class="file-preview-content">
        <pre v-if="filePreviewContent">{{ filePreviewContent }}</pre>
        <div v-else class="loading-text">正在加载文件内容...</div>
      </div>
      <div class="dialog-footer">
        <div class="encoding-info" v-if="encodingInfo">
          <el-tag size="small">{{ encodingInfo }}</el-tag>
        </div>
        <el-button @click="filePreviewVisible = false">关闭</el-button>
        <el-button type="primary" @click="checkFileEncoding" :disabled="!filePreviewContent">
          检测编码
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import apiService from '../services/api'

// 状态管理
const processMode = ref('oneStop') // 处理模式: oneStop(一站式) 或 stepByStep(分步处理)
const inputMode = ref('text') // 输入方式: text(文本输入) 或 file(文件上传)
const textContent = ref('') // 文本内容
const fileList = ref([]) // 文件列表
const loading = ref(false) // 加载状态
const loadingText = ref('处理中...') // 加载提示文本
const progressPercentage = ref(0) // 进度百分比
const serviceStatus = ref('checking') // 服务状态: checking(检查中), ok(正常), error(错误)
const activeCollapse = ref(['step1']) // 当前打开的折叠面板

// 结果状态
const fullResult = ref(null) // 一站式处理结果
const step1Result = ref(null) // 提取键结构结果
const step2Result = ref(null) // 匹配模板结果
const step3Result = ref(null) // 完整病历JSON结果

// 加载状态计时
const loadingStartTime = ref(0);
const loadingTime = ref(0);
const loadingTimer = ref(null);

// 启动加载计时器
const startLoadingTimer = () => {
  loadingStartTime.value = Date.now();
  loadingTime.value = 0;
  
  // 清除可能存在的旧计时器
  if (loadingTimer.value) {
    clearInterval(loadingTimer.value);
  }
  
  // 创建新计时器，每秒更新一次
  loadingTimer.value = setInterval(() => {
    loadingTime.value = (Date.now() - loadingStartTime.value) / 1000;
  }, 1000);
};

// 停止加载计时器
const stopLoadingTimer = () => {
  if (loadingTimer.value) {
    clearInterval(loadingTimer.value);
    loadingTimer.value = null;
  }
  loadingTime.value = 0;
};

// 监听loading状态变化
watch(loading, (newVal) => {
  if (newVal) {
    // 开始加载
    startLoadingTimer();
  } else {
    // 结束加载
    stopLoadingTimer();
  }
});

// 组件卸载时清除计时器
onUnmounted(() => {
  stopLoadingTimer();
});

// 计算属性
const canProcess = computed(() => {
  return inputMode.value === 'text' ? textContent.value.trim().length > 0 : fileList.value.length > 0;
});

// 文件预览相关
const filePreviewVisible = ref(false);
const filePreviewContent = ref('');
const encodingInfo = ref('');

// 处理结果

// 处理文件上传变化
const handleFileChange = (file) => {
  fileList.value = [file.raw];
};

// 处理文件移除
const handleFileRemove = () => {
  fileList.value = [];
};

// 一站式处理病历
const processRecord = async () => {
  if (processMode.value === 'oneStop') {
    await processOneStop();
  } else {
    await extractKeys(); // 分步处理从第一步开始
  }
};

// 检查服务连接状态
const checkServiceStatus = async () => {
  serviceStatus.value = 'checking';
    try {
      await apiService.healthService.checkHealthAll();
    serviceStatus.value = 'ok';
    ElMessage.success('后端服务连接正常');
  } catch (error) {
    serviceStatus.value = 'error';
    ElMessage.error('无法连接到后端服务，请确保服务已启动');
  }
};

// 预览文件内容
const previewFileContent = async () => {
  if (!fileList.value || fileList.value.length === 0) {
    ElMessage.warning('请先选择文件');
      return;
    }
    
  filePreviewVisible.value = true;
  filePreviewContent.value = '';
  encodingInfo.value = '';
  
  try {
    const content = await readFileContent(fileList.value[0]);
    filePreviewContent.value = content;
  } catch (error) {
    ElMessage.error('读取文件失败');
    filePreviewContent.value = '无法读取文件内容';
  }
};

// 检测文本编码问题
const detectTextEncoding = async () => {
  if (!textContent.value) {
    ElMessage.warning('请先输入文本内容');
    return;
  }
  
  try {
    loading.value = true;
    loadingText.value = '正在检测文本编码...';
    progressPercentage.value = 50;
    loadingStartTime.value = Date.now(); // 记录开始时间
    
    const result = await apiService.templateService.detectEncoding(textContent.value);
    
    if (result.data && result.data.isFixed) {
      ElMessage.success('检测到编码问题并已修复');
      // 更新为修复后的文本
      if (result.data.fixedSample) {
        const fixed = await apiService.templateService.detectEncoding(textContent.value);
        textContent.value = fixed.data.fixedText || textContent.value;
      }
    } else {
      ElMessage.info('未检测到编码问题');
    }
  } catch (error) {
    ElMessage.error('检测编码失败');
  } finally {
    loading.value = false;
    loadingTime.value = 0; // 重置加载时间
  }
};

// 检测文件编码问题
const checkFileEncoding = async () => {
  if (!filePreviewContent.value) {
    ElMessage.warning('没有可检测的文件内容');
      return;
    }
    
  try {
    const result = await apiService.templateService.detectEncoding(filePreviewContent.value);
    
    if (result.data && result.data.isFixed) {
      encodingInfo.value = '检测到编码问题，可能需要转换';
      ElMessage({
        message: '文件可能存在编码问题，处理时系统将尝试自动修复',
        type: 'warning',
        duration: 5000
      });
    } else {
      encodingInfo.value = '文件编码正常';
      ElMessage.success('文件编码正常');
    }
  } catch (error) {
    ElMessage.error('检测编码失败');
  }
};

// 下载JSON结果
const downloadJSON = (data, filename) => {
  const jsonStr = typeof data === 'string' ? data : JSON.stringify(data, null, 2);
  const blob = new Blob([jsonStr], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
  
  ElMessage.success(`已下载 ${filename}`);
};

// 格式化JSON显示
const formatJSON = (jsonString) => {
  try {
    const obj = typeof jsonString === 'string' ? JSON.parse(jsonString) : jsonString;
    return JSON.stringify(obj, null, 2);
  } catch (e) {
    return jsonString;
  }
};

// 复制内容到剪贴板
const copyToClipboard = (text) => {
  const textarea = document.createElement('textarea');
  textarea.value = typeof text === 'string' ? text : JSON.stringify(text, null, 2);
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
  ElMessage.success('已复制到剪贴板');
};

// 重置处理结果
const resetResults = () => {
  fullResult.value = null;
  step1Result.value = null;
  step2Result.value = null;
  step3Result.value = null;
};

// 重置全部
const resetAll = () => {
  textContent.value = '';
  fileList.value = [];
  resetResults();
};

// 读取文件内容为文本
const readFileContent = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => resolve(e.target.result);
    reader.onerror = (e) => reject(e);
    reader.readAsText(file);
  });
};

// 一站式处理
const processOneStop = async () => {
  try {
    loading.value = true;
    loadingText.value = '检查服务连接...';
    progressPercentage.value = 10;
    
    // 先检查健康状态
    try {
      await apiService.healthService.checkHealthAll();
      console.log('后端服务连接正常');
      serviceStatus.value = 'ok';
    } catch (error) {
      ElMessage.error('无法连接到后端服务，请确保服务已启动');
      console.error('健康检查失败:', error);
      serviceStatus.value = 'error';
      loading.value = false;
      return;
    }

    // 检测编码问题
    if (inputMode.value === 'text' && textContent.value.includes('')) {
      loadingText.value = '检测并修复文本编码...';
      progressPercentage.value = 20;
      
      try {
        const encodingResult = await apiService.templateService.detectEncoding(textContent.value);
        if (encodingResult.data && encodingResult.data.isFixed) {
          ElMessage.info('检测到文本存在编码问题，已尝试修复');
        }
      } catch (error) {
        console.warn('编码检测失败:', error);
        // 编码检测失败不影响后续流程
      }
    }
    
    loadingText.value = '正在进行一站式病历处理...';
    progressPercentage.value = 30;
    
    // 显示长时间处理提示
    setTimeout(() => {
      if (loading.value) {
        loadingText.value = '正在处理数据，这可能需要较长时间...';
        progressPercentage.value = 50;
      }
    }, 5000);
    
    setTimeout(() => {
      if (loading.value) {
        loadingText.value = '正在与AI模型交互，请耐心等待...';
        progressPercentage.value = 70;
        
        // 显示提示对话框
        ElMessage({
          message: '大型文本处理可能需要较长时间，请不要关闭页面',
          type: 'warning',
          duration: 5000
        });
      }
    }, 15000);
    
    let result;
    
    try {
      if (inputMode.value === 'text') {
        // 文本输入方式
        result = await apiService.templateService.processText(textContent.value);
      } else {
        // 文件上传方式
        if (!fileList.value || fileList.value.length === 0) {
          ElMessage.error('请选择要上传的文件');
          loading.value = false;
          return;
        }
        result = await apiService.templateService.processFile(fileList.value[0]);
      }
    } catch (error) {
      if (error.code === 'ECONNABORTED') {
        ElMessage.error('请求超时，后端处理时间过长。请尝试使用分步处理或减少文本量');
        console.error('请求超时:', error);
        return;
      }
      throw error; // 其他错误继续向上抛出
    }
    
    progressPercentage.value = 100;
    fullResult.value = result.data || result;
    ElMessage.success('处理成功');
  } catch (error) {
    let errorMsg = '处理失败';
    if (error.response && error.response.data) {
      if (error.response.data.message) {
        errorMsg += `: ${error.response.data.message}`;
      } else if (typeof error.response.data === 'string') {
        errorMsg += `: ${error.response.data}`;
      }
    } else if (error.message) {
      errorMsg += `: ${error.message}`;
    }
    ElMessage.error(errorMsg);
    console.error('处理失败:', error);
  } finally {
    loading.value = false;
  }
};

// 步骤1: 提取键结构
const extractKeys = async () => {
  try {
    loading.value = true;
    loadingText.value = '检查服务连接...';
    progressPercentage.value = 10;
    
    // 先检查健康状态
    try {
      await apiService.healthService.checkHealth();
      console.log('后端服务连接正常');
      serviceStatus.value = 'ok';
    } catch (error) {
      ElMessage.error('无法连接到后端服务，请确保服务已启动');
      console.error('健康检查失败:', error);
      serviceStatus.value = 'error';
      loading.value = false;
      return;
    }
    
    // 检测编码问题
    if (inputMode.value === 'text' && textContent.value.includes('')) {
      loadingText.value = '检测并修复文本编码...';
      progressPercentage.value = 20;
      
      try {
        const encodingResult = await apiService.templateService.detectEncoding(textContent.value);
        if (encodingResult.data && encodingResult.data.isFixed) {
          ElMessage.info('检测到文本存在编码问题，已尝试修复');
        }
      } catch (error) {
        console.warn('编码检测失败:', error);
        // 编码检测失败不影响后续流程
      }
    }
    
    loadingText.value = '正在提取病历键结构...';
    progressPercentage.value = 30;
    
    // 显示长时间处理提示
    setTimeout(() => {
      if (loading.value) {
        loadingText.value = '正在分析文本结构，这可能需要较长时间...';
        progressPercentage.value = 50;
      }
    }, 5000);
    
    setTimeout(() => {
      if (loading.value) {
        loadingText.value = '正在与AI模型交互，请耐心等待...';
        progressPercentage.value = 70;
        
        // 显示提示对话框
        ElMessage({
          message: '大型文本处理可能需要较长时间，请不要关闭页面',
          type: 'warning',
          duration: 5000
        });
      }
    }, 15000);
    
    let result;
    
    try {
      if (inputMode.value === 'text') {
        result = await apiService.templateService.extractKeysFromText(textContent.value);
      } else {
        if (!fileList.value || fileList.value.length === 0) {
          ElMessage.error('请选择要上传的文件');
          loading.value = false;
          return;
        }
        result = await apiService.templateService.extractKeysFromFile(fileList.value[0]);
      }
    } catch (error) {
      if (error.code === 'ECONNABORTED') {
        ElMessage.error('请求超时，后端处理时间过长。请尝试减少文本量');
        console.error('请求超时:', error);
        return;
      }
      throw error; // 其他错误继续向上抛出
    }
    
    progressPercentage.value = 100;
    step1Result.value = result.data || result;
    activeCollapse.value = ['step2']; // 自动打开下一步
    ElMessage.success('键结构提取成功');
  } catch (error) {
    let errorMsg = '提取键结构失败';
    if (error.response && error.response.data) {
      if (error.response.data.message) {
        errorMsg += `: ${error.response.data.message}`;
      } else if (typeof error.response.data === 'string') {
        errorMsg += `: ${error.response.data}`;
      }
    } else if (error.message) {
      errorMsg += `: ${error.message}`;
    }
    ElMessage.error(errorMsg);
    console.error('提取键结构失败:', error);
  } finally {
    loading.value = false;
  }
};

// 步骤2: 匹配模板
const matchTemplate = async () => {
  try {
    loading.value = true;
    loadingText.value = '正在匹配病历模板...';
    progressPercentage.value = 30;
    
    if (!step1Result.value) {
      ElMessage.error('请先完成键结构提取步骤');
      loading.value = false;
      return;
    }
    
    // 显示长时间处理提示
    setTimeout(() => {
      if (loading.value) {
        loadingText.value = '正在进行模板匹配，这可能需要较长时间...';
        progressPercentage.value = 60;
      }
    }, 5000);
    
    setTimeout(() => {
      if (loading.value) {
        loadingText.value = '正在与知识库交互，请耐心等待...';
        progressPercentage.value = 80;
      }
    }, 15000);
    
    let result;
    try {
      result = await apiService.templateService.matchTemplate(step1Result.value);
    } catch (error) {
      if (error.code === 'ECONNABORTED') {
        ElMessage.error('请求超时，后端处理时间过长');
        console.error('请求超时:', error);
        return;
      }
      throw error; // 其他错误继续向上抛出
    }
    
    progressPercentage.value = 100;
    step2Result.value = result.data || result;
    activeCollapse.value = ['step3']; // 自动打开下一步
    ElMessage.success('模板匹配成功');
  } catch (error) {
    let errorMsg = '匹配模板失败';
    if (error.response && error.response.data) {
      if (error.response.data.message) {
        errorMsg += `: ${error.response.data.message}`;
      } else if (typeof error.response.data === 'string') {
        errorMsg += `: ${error.response.data}`;
      }
    } else if (error.message) {
      errorMsg += `: ${error.message}`;
    }
    ElMessage.error(errorMsg);
    console.error('匹配模板失败:', error);
  } finally {
    loading.value = false;
  }
};

// 步骤3: 生成完整病历JSON
const generateFullRecord = async () => {
  try {
    loading.value = true;
    loadingText.value = '正在生成完整病历JSON...';
    progressPercentage.value = 30;
    
    if (!step2Result.value) {
      ElMessage.error('请先完成模板匹配步骤');
      loading.value = false;
      return;
    }
    
    let originalText;
    
    if (inputMode.value === 'text') {
      originalText = textContent.value;
    } else {
      // 读取文件内容
      originalText = await readFileContent(fileList.value[0]);
    }
    
    // 显示长时间处理提示
    setTimeout(() => {
      if (loading.value) {
        loadingText.value = '正在生成结构化数据，这可能需要较长时间...';
        progressPercentage.value = 60;
      }
    }, 5000);
    
    setTimeout(() => {
      if (loading.value) {
        loadingText.value = '正在与AI模型交互，请耐心等待...';
        progressPercentage.value = 80;
      }
    }, 15000);
    
    let result;
    try {
      result = await apiService.templateService.generateFullRecord(originalText, step2Result.value);
    } catch (error) {
      if (error.code === 'ECONNABORTED') {
        ElMessage.error('请求超时，后端处理时间过长');
        console.error('请求超时:', error);
        return;
      }
      throw error; // 其他错误继续向上抛出
    }
    
    progressPercentage.value = 100;
    step3Result.value = result.data || result;
    ElMessage.success('完整病历JSON生成成功');
  } catch (error) {
    let errorMsg = '生成完整病历JSON失败';
    if (error.response && error.response.data) {
      if (error.response.data.message) {
        errorMsg += `: ${error.response.data.message}`;
      } else if (typeof error.response.data === 'string') {
        errorMsg += `: ${error.response.data}`;
      }
    } else if (error.message) {
      errorMsg += `: ${error.message}`;
    }
    ElMessage.error(errorMsg);
    console.error('生成完整病历JSON失败:', error);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.medical-record-parser {
  width: 100%;
  margin: 0 auto;
  padding: 0;
}

.parser-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-section {
  flex: 1;
}

.page-title {
  font-size: 24px;
  margin-bottom: 10px;
  color: #303133;
  margin-top: 0;
}

.page-desc {
  color: #606266;
  margin-bottom: 0;
}

.process-mode {
  margin-left: 20px;
}

/* 左右布局样式 */
.main-content-layout {
  display: flex;
  gap: 30px;
  margin-top: 20px;
}

.input-section {
  flex: 0.8;
  min-width: 300px;
  max-width: 40%;
}

.result-section {
  flex: 1.2;
  min-width: 350px;
  border-left: 1px solid #eaeaea;
  padding-left: 30px;
}

.section-title {
  font-size: 18px;
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
  font-weight: 500;
}

.input-mode-tabs {
  margin-bottom: 20px;
  width: 100%;
}

.text-input-container {
  display: flex;
  flex-direction: column;
}

.text-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  gap: 10px;
}

.upload-area {
  width: 100%;
}

.file-info {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 0;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  width: 100%;
}

.loading-text {
  margin-top: 15px;
  color: #606266;
  text-align: center;
  font-size: 16px;
}

.loading-tip {
  font-size: 14px;
  color: #909399;
  margin-top: 8px;
}

.loading-tip.warning {
  color: #E6A23C;
  font-weight: bold;
}

.service-status {
  margin-bottom: 15px;
}

.result-content {
  margin-top: 0;
}

.json-result {
  margin-top: 0;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.json-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  background-color: #f5f7fa;
  border-bottom: none;
}

.json-actions {
  display: flex;
  gap: 10px;
}

.json-output {
  padding: 15px;
  background-color: #f8f8f8;
  max-height: 600px;
  min-height: 300px;
  overflow: auto;
  font-family: monospace;
  white-space: pre-wrap;
  word-break: break-word;
  margin: 0;
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  border-top: 1px solid #e4e7ed;
}

.step-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.step-number {
  background-color: #409EFF;
  color: white;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

.step-title {
  font-weight: bold;
}

.step-action {
  margin: 10px 0;
}

.step-result {
  margin-top: 10px;
}

/* 文件预览对话框样式 */
.file-preview-content {
  max-height: 600px; /* 增加预览内容区域的高度 */
  overflow-y: auto; /* 允许内容区域滚动 */
  padding: 10px;
  background-color: #f8f8f8;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  font-family: monospace;
  white-space: pre-wrap;
  word-break: break-word;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.encoding-info {
  margin-right: 10px;
}

/* 响应式布局 */
@media (max-width: 992px) {
  .parser-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .process-mode {
    margin-left: 0;
    margin-top: 15px;
  }
  
  .main-content-layout {
    flex-direction: column;
  }
  
  .input-section, 
  .result-section {
    max-width: 100%;
    padding-left: 0;
    border-left: none;
  }
  
  .result-section {
    margin-top: 30px;
    border-top: 1px solid #eaeaea;
    padding-top: 20px;
  }
}
</style> 